const Koa = require('koa');
const Router = require('koa-Router')
const bodyparser = require('koa-bodyparser')
const cors = require('koa-cors')
const jwt = require('jsonwebtoken')
const Mock = require('mockjs')
const url = require('url')
const qs = require('querystring')

const userData = require('./user.json')
const roleData = require('./role.json')
const routerData = require('./router.json')
const path = require('path')
const fs = require('fs')

const app = new Koa();
const router = new Router()

app.use(bodyparser())
app.use(cors())

// 登录接口
router.post('/login', ctx => {
    // 获取页面传过来的用户和密码
    let { username, password } = ctx.request.body
    // 读取本地的用户json数据
    let userData = fs.readFileSync(path.join(__dirname, './user.json'), 'utf-8')
    // 将json字符串转成js对象
    let userArr = JSON.parse(userData)
    //在数据库中查找是否有符合前端传过来的数据
    let bool = userArr.some(item => item.username == username && item.password == password)
    // 如果没有返回错误
    if (!bool) {
        return ctx.body = {
            code: 400,
            msg: '账号或密码有错误'
        }
    }
    // 在数据库中找到当前用户所具备的权限
    const user = userArr.find(item => item.username == username)
    const roleDatapath = fs.readFileSync(path.join(__dirname, './role.json'), 'utf-8')
    const roleDataArr = JSON.parse(roleDatapath)
    const role = roleDataArr.find(item => item.id == user.roleId)
    // 根据role中的auth权限在router中筛选对应的所有对象
    const routerDatapath = fs.readFileSync(path.join(__dirname, './router.json'), 'utf-8')
    let routerDataArr = JSON.parse(routerDatapath)
    // 如果role.auth==* 获取这个routerDataArr（全部路径）
    // 如果role.auth!=="*" 则通过role中的auth权限 在routerDataArr筛选对应的对象
    if (role.auth !== "*") {
        routerDataArr = routerDataArr.filter(item => role.auth.includes(item.id))
    }

    // token
    let token = jwt.sign({
        username,
        startTime: +new Date,
        expires: 7200 * 1000
    }, 'asdfsgfgf')

    return ctx.body = {
        code: 200,
        msg: '登陆成功',
        token,
        username,
        userId: user.id,
        auth: routerDataArr
    }
})


// 用户数据接口
router.get('/userlist', ctx => {
    let userData = fs.readFileSync(path.join(__dirname, './user.json'), 'utf-8')
    // 将json字符串转成js对象
    let userArr = JSON.parse(userData)

    const roleDatapath = fs.readFileSync(path.join(__dirname, './role.json'), 'utf-8')
    let roleDataArr = JSON.parse(roleDatapath)

    userArr = userArr.map((item) => {
        let roles = roleDataArr.find(v => v.id == item.roleId)
        item.rolename = roles.role
        return item
    })
    //   console.log(userArr);

    ctx.body = {
        code: 200,
        msg: '获取成功',
        data: userArr
    }
})


// 用户添加
router.post('/useradd', ctx => {
    let { username, password, roleId } = ctx.request.body
    // console.log(username,password,roleId);
    let userpath = fs.readFileSync(path.join(__dirname, './user.json'), 'utf-8')
    let userArr = JSON.parse(userpath)
    userArr.push({
        id: +new Date(),
        username,
        password,
        roleId
    })
    fs.writeFileSync(path.join(__dirname, './user.json'), JSON.stringify(userArr))
    ctx.body = {
        code: 200,
        msg: '添加成功'
    }
})


// 编辑用户接口
router.post('/useredit', ctx => {
    let { id, roleId, username, password } = ctx.request.body
    // console.log(id,roleId,username,password)
    let userpath = fs.readFileSync(path.join(__dirname, './user.json'), 'utf-8')
    let userArr = JSON.parse(userpath)
    let aa = userArr.find(item => item.id == id)
    aa.username = username
    aa.password = password
    aa.roleId = roleId
    fs.writeFileSync(path.join(__dirname, './user.json'), JSON.stringify(userArr))
    ctx.body = {
        code: 200,
        msg: '成功'
    }
})


// 用户删除
router.get('/userdel', ctx => {
    // 获取路径
    const {query}=url.parse(ctx.request.url)
    // 获取Id
    let {id}=qs.parse(query)
    console.log(id, "id")
    let userpath = fs.readFileSync(path.join(__dirname, './user.json'), 'utf-8')
    let userArr = JSON.parse(userpath)
    // 找到删除对象的下标
    userArrIndex = userArr.findIndex(item => item.id == id)
    console.log(userArrIndex, "下标")
    // 删除找到的下标
    userArr.splice(userArrIndex, 1)
    //    console.log(userArr,33336)

    //  userArr=userArr.filter(item=>item.id!=id)
    fs.writeFileSync(path.join(__dirname, './user.json'), JSON.stringify(userArr))
    ctx.body = {
        code: 200,
        msg: '删除成功'
    }
})



//获取角色
router.get('/role/list', ctx => {
    const roleDatapath = fs.readFileSync(path.join(__dirname, './role.json'), 'utf-8')
    const roleDataArr = JSON.parse(roleDatapath)
    ctx.body =
    {
        code: 200,
        msg: '获取角色',
        data: roleDataArr
    }
}
)


// 获取router
router.get('/routerList', ctx => {
    const data = roleData.map(item => {
        if (item.auth !== '*') {
            item.auths = routerData.filter(v => item.auth.includes(v.id))
            // item.auths=routerData

        } else {
            item.auths = routerData
        }
        return item
    })
    //    console.log(data,'0000')
    ctx.body = {
        code: 200,
        msg: '获取成功',
        data: data
    }
})

// role 角色添加
router.post('/roleAdd', ctx => {
    let { username, auth } = ctx.request.body;
    const roleDatapath = fs.readFileSync(path.join(__dirname, './role.json'), 'utf-8')
    let roleDataArr = JSON.parse(roleDatapath)
    roleDataArr.push({
        id: +new Date(),
        role: username,
        auth: auth
    })
    fs.writeFileSync(path.join(__dirname, './role.json'), JSON.stringify(roleDataArr))
    ctx.body={
        code:200,
        msg:'添加成功'
    }
})


// role 角色删除
router.get('/roledel',ctx=>{
    // 获取路径
    const {query}=url.parse(ctx.request.url)
    // 获取Id
    let {id}=qs.parse(query)
    console.log(id,"roledel")
    const roleDataStr=fs.readFileSync(path.join(__dirname,'./role.json'),'utf-8')
    let roleDataArr=JSON.parse(roleDataStr)
    let index=roleDataArr.findIndex(item=>item.id==id)
    roleDataArr.splice(index,1)
    fs.writeFileSync(path.join(__dirname,'./role.json'),JSON.stringify(roleDataArr))
    ctx.body={
        code:200,
        msg:'删除成功'
    }
})


// role 获取单个数据的接口
router.get('/roleone',ctx=>{
    const {query}=url.parse(ctx.request.url)
    let {id}=qs.parse(query)
    console.log(id,"roleone")
    const roleDataStr=fs.readFileSync(path.join(__dirname,'./role.json'),'utf-8')
    let roleDataArr=JSON.parse(roleDataStr)
    let role=roleDataArr.find(item=>item.id==id)
    ctx.body={
        code:200,
        msg:'获取成功',
        data:role
    }
})

app.use(router)
app.listen(3000);